/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙，邂逅框架梦]
 * 
 * https://zhiqim.org/project/zhiqim_framework/zhiqim_kernel.htm
 *
 * Zhiqim Kernel is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.zhiqim.kernel.json.parser;

import java.util.Calendar;
import java.util.Date;

import org.zhiqim.kernel.json.JsonParser;
import org.zhiqim.kernel.json.Jsons;
import org.zhiqim.kernel.util.DateTimes;
import org.zhiqim.kernel.util.Sqls;

/**
 * 日期解析器：
 * 1、优先sql.Date,sql.Time,sql.Timestamp
 * 2、其次Date,Calendar
 *
 * @version v1.0.0 @author zouzhigang 2014-3-21 新建与整理
 */
public class DateParser implements JsonParser
{
    @Override
    public String toString(Object obj)
    {
        if (obj instanceof java.sql.Date)
        {
            java.sql.Date date = (java.sql.Date)obj;
            return "\""+DateTimes.toDateString(date)+"\"";
        }
        else if (obj instanceof java.sql.Time)
        {
            java.sql.Time time = (java.sql.Time)obj;
            return "\""+DateTimes.toTimeString(time)+"\"";
        }
        else if (obj instanceof java.sql.Timestamp)
        {
            java.sql.Timestamp time = (java.sql.Timestamp)obj;
            return "\""+DateTimes.toDateTimeString(time)+"\"";
        }
        else if (obj instanceof Date)
        {
            Date date = (Date)obj;
            return "\""+DateTimes.toDateTimeString(date)+"\"";
        }
        else if (obj instanceof Calendar)
        {
            Calendar calendar = (Calendar)obj;
            return "\""+DateTimes.toDateTimeString(calendar)+"\"";
        }
        
        return null;
    }

    @Override
    public Object toObject(String json, Class<?> cls)
    {
        json = Jsons.removeStartEndQuotation(json);
        
        if (cls == java.sql.Date.class)
        {
            return Sqls.toDate(json);
        }
        else if (cls == java.sql.Time.class)
        {
            return Sqls.toTime(json);
        }
        else if (cls == java.sql.Timestamp.class)
        {
            return Sqls.toTimestamp(json);
        }
        else if (cls == Date.class)
        {
            return DateTimes.toDate(json);
        }
        else if (cls == Calendar.class)
        {
            return DateTimes.toCalendar(json);
        }
        
        return null;
    }
}
